package com.sharp.core.math.primitives;

import com.sharp.core.math.Vec3;
import com.sharp.core.math.Vectors3D;
import com.sharp.core.raytrace.Ray;

import static com.sharp.core.math.Trig.*;

public class Sphere extends Primitive {

	private float radius;
	
	////////////////////////////
	private Vec3 dist;
	
	////////////////////////////
	private Vec3 normal;
	
	public Sphere() {
		radius = 10;
		dist = new Vec3();
		
		normal = new Vec3();
	}
	
	public Sphere(float r) {
		this();
		radius = r;
	}
	
	@Override
	public float intersect(Ray ray) {
		float t = 2000;
		dist.setTo(ray.getOrigin(), getPos());;
		float B = Vectors3D.dotProduct(dist, ray.getDir());
		float D = B*B - Vectors3D.dotProduct(dist, dist) + radius*radius;
	    if (D < 0.0f) 
	        return -1; 
	    float t0 = (float) (B - sqrt(D)); 
	    float t1 = (float) (B + sqrt(D));
	    if ((t0 > 0.1f) && (t0 < t)) 
	    {
	        return t0;
	    } 
	    if ((t1 > 0.1f) && (t1 < t)) 
	    {
	    	return t1;
	    }
	    return -1;
	}

	@Override
	public String toString() {
		return "Sphere("+radius+")"+super.toString();
	}

	@Override
	public Vec3 normal(Vec3 pos) {
		normal.setTo(getPos(), pos);
		//normal.normalize();
		normal.divide(radius);
		
		return normal;
	}

	public float getRadius() {
		return radius;
	}

	public void setRadius(float radius) {
		this.radius = radius;
	}
	
}
